package com.yyplatform.admin.platform.role.service;

import java.util.List;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StringUtils;
import com.yyplatform.admin.infra.exception.ErrorCode;
import com.yyplatform.admin.infra.exception.ServiceException;
import com.yyplatform.admin.platform.role.model.dto.SysUserUploadDTO;
import com.yyplatform.admin.platform.role.model.enums.UserGenderEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2025-04-16
 */
@Slf4j
public class UploadUserDataListener implements ReadListener<SysUserUploadDTO> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private SysUserService sysUserService;
    private List<SysUserUploadDTO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    public UploadUserDataListener(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }


    @Override
    public void invoke(SysUserUploadDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", data);

        if (StringUtils.isEmpty(data.getUsername())
                || StringUtils.isEmpty(data.getRealName())
                || StringUtils.isEmpty(data.getPhone())
                || StringUtils.isEmpty(data.getGender())
                || StringUtils.isEmpty(data.getNickname())) {
            throw ServiceException.of(ErrorCode.PARAM_INVALID);
        }

        if (!StringUtils.equals(data.getGender(), UserGenderEnum.MALE.getValue())
                && !StringUtils.equals(data.getGender(), UserGenderEnum.FEMALE.getValue())) {
            throw ServiceException.of(ErrorCode.PARAM_INVALID);
        }


        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }


    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        sysUserService.saveUploadData(cachedDataList);
        log.info("存储数据库成功！");
    }

}
